import apiConfig from "../../utils/api.js";

Page({
  data: {
    imgBaseUrl: "",
    iconBaseUrl: "",
    videoBaseUrl: "",
    currentVideoSrc: "",
    // 角色类型：male/female
    characterType: "male",
    // 视频播放状态
    isMainVideoPlayed: false,
    // 流式输出相关
    currentReply: "",
    isStreaming: false,
    // 底部模块
    features: [],
    // 故事列表
    stories: [],
  },

  onLoad() {
    // 从全局变量获取性别设置
    const app = getApp();
    const gender = app.globalData.gender || "male";
    console.log(gender)
    const iconBaseUrl = apiConfig.ENV.iconBaseUrl;
    const videoBaseUrl = apiConfig.ENV.videoBaseUrl;
    const imgBaseUrl = apiConfig.ENV.imgBaseUrl;
    
    this.setData({
      iconBaseUrl: iconBaseUrl,
      imgBaseUrl: imgBaseUrl,
      videoBaseUrl: videoBaseUrl,
      characterType: gender,
      currentVideoSrc: videoBaseUrl + 'index-IP-' + gender + '.mp4',
      features: [
        {
          id: "chatting",
          title: "智趣问答",
          icon: iconBaseUrl + "icon-IPchatting.png",
        },
        {
          id: "culture",
          title: "故事点播",
          icon: iconBaseUrl + "icon-IPdianbo.png",
        },
        {
          id: "wenwu",
          title: "历史文物",
          icon: iconBaseUrl + "icon-IPwenwu.png",
        },
        { id: "", title: "思政IP课堂", icon: iconBaseUrl + "icon-class.png" },
        {
          id: "",
          title: "虚拟校园活动",
          icon: iconBaseUrl + "icon-huodong.png",
        },
        {
          id: "",
          title: "社会实践策划",
          icon: iconBaseUrl + "icon-shijian.png",
        },
      ],
    });
  },

  onReady() {
    this.videoContext = wx.createVideoContext("bgVideo", this);
    if (this.videoContext && typeof this.videoContext.play === "function") {
      try {
        this.videoContext.play();
      } catch (e) {
        console.warn(e);
      }
    }

    this.startConversation();
  },

  // 视频播放结束事件处理
  onVideoEnded() {
    // 如果是主视频播放结束，则切换到循环视频
    if (!this.data.isMainVideoPlayed) {
      this.setData({
        currentVideoSrc: this.data.videoBaseUrl + 'index-IP-' + this.data.characterType + 'huishou.mp4',
        isMainVideoPlayed: true
      });
      
      // 重新播放循环视频
      setTimeout(() => {
        if (this.videoContext) {
          this.videoContext.play();
        }
      }, 100);
    }
  },

  // 切换角色类型
  switchCharacter(characterType) {
    this.setData({
      characterType: characterType,
      isMainVideoPlayed: false,
      currentVideoSrc: this.data.videoBaseUrl + 'index-IP-' + characterType + '.mp4'
    });
    
    // 重新播放视频
    setTimeout(() => {
      if (this.videoContext) {
        this.videoContext.play();
      }
    }, 100);
  },

  startConversation() {
    const sampleReply =
      "先辈筚路蓝缕拓荒兴学，这份融于血脉的“652”精神——胸怀天下之家国情怀、舍我其谁之使命担当、自强不息之开拓奋进，等你解锁！点击故事点播听热血往事，历史文物看校史老物件，读懂属于我们的荣光!";
    setTimeout(() => {
      this.stopStream();
      this.startStream(sampleReply, 200);
    }, 1000);
  },

  startStream(text = "", interval = 40) {
    if (!text) return;
    this.setData({ currentReply: "", isStreaming: true });
    let i = 0;
    if (this._streamTimer) clearInterval(this._streamTimer);
    this._streamTimer = setInterval(() => {
      i++;
      const slice = text.slice(0, i);
      this.setData({ currentReply: slice });
      if (i >= text.length) {
        this.stopStream();
      }
    }, interval);
  },

  stopStream() {
    if (this._streamTimer) {
      clearInterval(this._streamTimer);
      this._streamTimer = null;
    }
    this.setData({ isStreaming: false });
  },

  onFeatureTap(e) {
    const id = e.currentTarget.dataset.id;
    switch (id) {
      case "chatting":
        wx.navigateTo({ url: "/pages/chatting/chatting" });
        break;
      case "culture":
        console.log("click")
        wx.navigateTo({ url: "/pages/culture/culture" });
        break;
      case "wenwu":
        wx.navigateTo({ url: "/pages/wenwu/wenwu" });
        break;
      default:
        wx.showToast({ title: "功能开发中", icon: "none" });
    }
  },

  // Navigate to Mine page
  goToMine() {
    wx.navigateTo({ url: "/pages/mine/mine" });
  },

  // Navigate to Signup page
  goToSignup() {
    wx.showToast({ title: "功能开发中", icon: "none" });
  },

  // Navigate to Quiz page
  goToQuiz() {
    wx.showToast({ title: "功能开发中", icon: "none" });
  },

  goToChat() {
    wx.navigateTo({ url: "/pages/chatting/chatting" });
  },

  onUnload() {
    if (this._streamTimer) {
      clearInterval(this._streamTimer);
      this._streamTimer = null;
    }
  },

  formatTime(timeStr) {
    if (!timeStr) return "";
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}`; // 2025-10-11 12:21
  },
});